package com.itheima.test9;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Author:gy
 * @Date: 2025/09/04 15:12
 * @Description:
 */
public class ServerDemo {
    public static void main(String[] args) throws Exception {
        System.out.println("计算器服务已启动,等待连接");
        ServerSocket ss = new ServerSocket(54321);
        //监听服务
        Socket socket = ss.accept();
        System.out.println("客户端已经连接"+socket.getInetAddress());
        //创建网络的输入输出流
        //字符缓冲输入流
        BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        //字符缓冲输出流
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        String cala;
        while((cala =  br.readLine())!=null){
           // cala = br.readLine();
            System.out.println("已经收到计算请求:"+cala);
            if("exit".equals(cala)){
                break;
            }
            double resule =  jisuan(cala);
            if(Double.isInfinite(resule)){
                bw.write("除数不能为0");
                bw.newLine();
                bw.flush();
                //socket.shutdownOutput();
            }else{
                bw.write(resule+"\n");
                bw.flush();
                // socket.shutdownOutput();
            }
        }
    }

    private static double jisuan(String cala) {
        String replace = cala.trim();
        if(cala.contains("+")){
            String[] split = replace.split("\\+");
            double num1 = Double.parseDouble(split[0]);
            double num2 = Double.parseDouble(split[1]);
            return num1+num2;
        }else if(cala.contains("-")){
            String[] split = replace.split("-");
            double num1 = Double.parseDouble(split[0]);
            double num2 = Double.parseDouble(split[1]);
            return num1-num2;

        }else if(cala.contains("*")){
            String[] split = replace.split("\\*");
            double num1 = Double.parseDouble(split[0]);
            double num2 = Double.parseDouble(split[1]);
            return num1*num2;
        }else{
            String[] split = replace.split("/");
            double num1 = Double.parseDouble(split[0]);
            double num2 = Double.parseDouble(split[1]);
            return num1/num2;
            }
        }
    }

